package com.cdn.auth.filter;

import com.cdn.auth.config.CAuthProperties;
import com.cdn.auth.context.TokenManager;
import com.cdn.auth.context.UserContext;
import com.cdn.auth.exception.UnAuthorizedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 蔡定努
 * 2024/06/28 21:39
 */
public class UserContextFilter implements Filter {

    private static final Log log = LogFactory.getLog(UserContextFilter.class);
    @Autowired
    private CAuthProperties casProperties;

    @Resource
    private TokenManager tokenManager;

    ;
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public void init(FilterConfig filterConfig) {
        log.info("UserContextFilter init success");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            verifyPath(servletRequest, servletResponse);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.remove();
        }
    }


    /**
     * @author 蔡定努
     */
    private void verifyPath(ServletRequest servletRequest, ServletResponse servletResponse) {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String uri = request.getRequestURI();
            if (casProperties.getIgnoresPath().stream().anyMatch(pattern -> antPathMatcher.match(pattern, uri))) {
                return;
            }
            boolean isTokenValid = tokenManager.isValidToken(request);
            if (!isTokenValid) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                throw new UnAuthorizedException("未登录认证");
            }
            tokenManager.refreshToken();
        }
    }

    @Override
    public void destroy() {
        log.info("UserContextFilter destroy success");
    }
}
